package org.at.diary;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;

import org.at.nhatky1.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class NoteEdit extends Activity {

    private EditText edtTitle;
    private EditText edtBody;
    private TextView tvDate;
    private Spinner spnStatus;
    private String getTime;
    
    private Button btnShowTitle;
    private Button btnShowStatus;
    
    private int intStatus=0;
    private Long mRowId;
    private NotesDbAdapter mDbHelper;

    
    // Custom EditText
    
    public static class LinedEditText extends EditText {
        private Rect mRect;
        private Paint mPaint;

        // we need this constructor for LayoutInflater
        public LinedEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            
            mRect = new Rect();
            mPaint = new Paint();
            mPaint.setStyle(Paint.Style.STROKE);
        }
        
        @Override
        protected void onDraw(Canvas canvas) {
    		boolean fullWidth = true;
    		boolean textlines = true;
    		boolean pagelines = true;
        	if (textlines || pagelines) {
                mPaint.setColor(Color.BLACK);
        		
	            int count = getLineCount();
	            Rect r = mRect;
	            Paint paint = mPaint;
	
	            int height = getHeight();
	            int line_height = getLineHeight();
	            int page_size = height / line_height + 1;
	            
	            int baseline = 0;
	            int left = 0;
	            int right = 0;
	            for (int i = 0; i < count; i++) {
	                baseline = getLineBounds(i, r);
	                left = r.left;
	                right = r.right;
	                if (fullWidth) {
	                	left = getLeft();
	                	right = getRight();
	                }
                	canvas.drawLine(left, baseline + 1, right, baseline + 1, paint);
	            }
	            if (pagelines) {
	            	// Fill the rest of the page with lines
		            for (int i = count; i < page_size; i++) {
		            	baseline += line_height;
		                canvas.drawLine(left, baseline + 1, right, baseline + 1, paint);
		            }
	            }
        	}            
            super.onDraw(canvas);
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDbHelper = new NotesDbAdapter(this);
        mDbHelper.open();
        
        setContentView(R.layout.diary_edit);
        
        edtTitle = (EditText) findViewById(R.id.title);
        edtBody = (EditText) findViewById(R.id.body);
        btnShowTitle = (Button) findViewById(R.id.show_title);
        btnShowTitle.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				LinearLayout layoutTitle = (LinearLayout) findViewById(R.id.layout_title);
				if (layoutTitle.isShown()==false){
					layoutTitle.setVisibility(View.VISIBLE );
					btnShowTitle.setText(R.string.diary_hide_title);
				}
				else if (layoutTitle.isShown()==true){
					layoutTitle.setVisibility(View.GONE);
					btnShowTitle.setText(R.string.diary_show_title);
				}
				
				
			}
		});
        
        btnShowStatus = (Button) findViewById(R.id.show_status);
        btnShowStatus.setOnClickListener(new View.OnClickListener() {
			
			
			public void onClick(View v) {
				LinearLayout layoutStatus = (LinearLayout) findViewById(R.id.layout_status);
				if(layoutStatus.isShown() == false){
					layoutStatus.setVisibility(View.VISIBLE);
					btnShowStatus.setText(R.string.diary_hide_status);
				}
				else if (layoutStatus.isShown() == true){
					layoutStatus.setVisibility(View.GONE);
					btnShowStatus.setText(R.string.diary_show_status);
				}
				
			}
		});
        
        
        
        Button btnSave = (Button) findViewById(R.id.save);
        
        mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
        if (mRowId == null){
        	Bundle extras = getIntent().getExtras();
        	mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID):null;
        }
        
        getTime = getDateTimeCurrent();
        tvDate = (TextView) findViewById(R.id.diary_date);
        if (mRowId == null) tvDate.setText(getTime);
        loadStatus(intStatus);
        populateFields();
        
        btnSave.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                setResult(RESULT_OK);
                finish();
            }

        });
    }

    public void loadStatus(int pos){
    	spnStatus = (Spinner) findViewById(R.id.spn_status);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
        		this, R.array.status_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnStatus.setAdapter(adapter);
        spnStatus.setSelection(pos);
        intStatus = 0;
        spnStatus.setOnItemSelectedListener(new MyOnItemSelectedListener());
        
    }
    
    public class MyOnItemSelectedListener implements OnItemSelectedListener {

    	@Override
    	public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id)  {
    		// TODO Auto-generated method stub
    		intStatus = parent.getSelectedItemPosition();
    		
    	}

    	@Override
    	public void onNothingSelected(AdapterView<?> arg0) {
    		// TODO Auto-generated method stub

    	}

    }
	public void populateFields() {
		// TODO Auto-generated methfed stub
		if (mRowId != null){
			Cursor note = mDbHelper.fetchNote(mRowId);
			startManagingCursor(note);
			edtTitle.setText(note.getString(
                    note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
            edtBody.setText(note.getString(
                    note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
            loadStatus(note.getInt(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_STATUS)));
            tvDate.setText(note.getString(
            		note.getColumnIndexOrThrow(NotesDbAdapter.KEY_DATE)));
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		saveState();
		outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
	}
	
	// put the data  out to the database.
	private void saveState() {
		// TODO Auto-generated method stub
		String date_created = tvDate.getText().toString();
		String title = edtTitle.getText().toString();
		String body  = edtBody.getText().toString();
		int status = intStatus;
		if (title.equals("")){
			title = date_created;
		}
		
		if (mRowId == null){
			if (!body.equals("")){
				long id = mDbHelper.createNote(title, body, status, date_created);
				if (id > 0){
					mRowId = id;
				}
			}
		} 
		else mDbHelper.updateNote(mRowId, title, body, status, date_created);
		
	}

	protected String getDateTimeCurrent(){
		Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH)+1;
		String a =  calendar.get(Calendar.HOUR)+"h"
							+calendar.get(Calendar.MINUTE)+"' "
							+calendar.get(Calendar.DAY_OF_MONTH)+"/"
							+month+"/"
							+calendar.get(Calendar.YEAR)+"";
		return a;
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		saveState();
		mDbHelper.close();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		populateFields();
	}
	
	private static final int SAVE_TO_SDCARD = Menu.FIRST;
	private static final int DELETE = Menu.FIRST+1;
	private static final int FONT = Menu.FIRST+2;
	private static final int FONT_STYLE = Menu.FIRST+3;
	private static final int FONT_SIZE = Menu.FIRST+4;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuItem item_save = menu.add(Menu.NONE, SAVE_TO_SDCARD, Menu.NONE, R.string.save);
		item_save.setIcon(android.R.drawable.ic_menu_save);
		MenuItem item_delete = menu.add(Menu.NONE, DELETE, Menu.NONE, R.string.delete);
		item_delete.setIcon(android.R.drawable.ic_menu_delete);
		MenuItem item_font = menu.add(Menu.NONE, FONT, Menu.NONE, R.string.font);
		item_font.setIcon(R.drawable.font);
		MenuItem item_font_style = menu.add(Menu.NONE, FONT_STYLE, Menu.NONE, R.string.font_style);
		item_font_style.setIcon(R.drawable.font);
		MenuItem item_font_size = menu.add(Menu.NONE, FONT_SIZE, Menu.NONE, R.string.font_size);
		item_font_size.setIcon(R.drawable.font);
		return true;
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case DELETE:
			finish();
			return true;
		case SAVE_TO_SDCARD:
			saveToSDCard();
			return true;
		case FONT:
			chooseFont();
			return true;
		case FONT_STYLE:
			chooseFontStyle();
			return true;
		case FONT_SIZE:
			chooseFontSize();
		default:
			break;
		}
		
		
		return super.onOptionsItemSelected(item);
		
	}
	//private String fontStyle;

	private void chooseFontSize() {
		// TODO Auto-generated method stub
		//final Float f = edtBody.getTextSize();
		//Mặc đinh nó là 23 px
		String[] listFontSize = {"Cực nhỏ", "Nhỏ", "Bình thường", "Lớn", "Cực lớn"};
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.font_size_pick);
		builder.setSingleChoiceItems(listFontSize, -1, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
				case 0:
					edtBody.setTextSize(5);
					break;
				case 1: 
					edtBody.setTextSize(13);
					break;
				case 2: 
					edtBody.setTextSize(18);
					break;
				case 3:
					edtBody.setTextSize(23);
					break;
				case 4:
					edtBody.setTextSize(32);
					break;
				default:
					break;
				}
			}
		});
		builder.setPositiveButton(R.string.agree, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});
		builder.create();
		builder.show();
	}

	private void chooseFontStyle() {
		// TODO Auto-generated method stub
		final String [] listFontStyle = {"Bình thường", "Đậm", "Nghiêng", "Đậm và nghiêng"};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.font_style_pick)
			   .setSingleChoiceItems(listFontStyle, -1, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which) {
						case 0:
							edtBody.setTypeface(font, Typeface.NORMAL);
							break;
						case 1: 
							edtBody.setTypeface(font, Typeface.BOLD);
							break;
						case  2: 
							edtBody.setTypeface(font, Typeface.ITALIC);
							break;
						case 3:
							edtBody.setTypeface(font, Typeface.BOLD_ITALIC);
						default:
							break;
						}
						//fontStyle = listFontStyle[which];
						
					}
			   })
			.setCancelable(false)
			.setPositiveButton(R.string.agree, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
				}
			})
			.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.cancel();
				}
			})
			.create()
			.show();
			
		
	}

	private String numberOfFont[];
	private Typeface font;
	
	private void chooseFont() {
		// TODO Auto-generated method stub
		AssetManager am = this.getAssets();
		try {
			numberOfFont = am.list("fonts");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.font_pick);
		builder.setSingleChoiceItems(numberOfFont, -1, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				String a = numberOfFont[which];
				String fontPicked = "fonts/" + a;
				font = Typeface.createFromAsset(getAssets(),fontPicked);
				edtBody.setTypeface(font);
				
			}
		});
		builder.setCancelable(false);
		builder.setPositiveButton(R.string.agree, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
		builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});
		builder.create();
		builder.show();
	}
	
	

	private void saveToSDCard() {
		// TODO Auto-generated method stub

		if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
		    Toast.makeText(NoteEdit.this, "Không có thẻ nhớ hoặc chưa được mount. Vui lòng lắp thẻ nhớ để lưu tệp.", Toast.LENGTH_SHORT);
		} else {
			String title = edtTitle.getText().toString();
			if (title.equals("")){
				title = tvDate.getText().toString();
			}
			String filename = title + ".txt";
			filename = filename.replace("/", "");
			filename = filename.replace("\\", "");
			filename = filename.replace(":", "");
			filename = filename.replace("?", "");
			filename = filename.replace("*", "");
			File file = new File(NoteEdit.this.getExternalFilesDir("Nhatky"), filename);
			try {
				FileWriter fstream = new FileWriter(file);
				BufferedWriter out = new BufferedWriter(fstream);
				out.write("Nội dung: " + edtBody.getText().toString() + "\n");
				out.write("Ngày viết: " + tvDate.getText().toString() + "\n");
				out.write("Tâm trạng: " + spnStatus.getTag(intStatus));
				out.close();
				Toast.makeText(NoteEdit.this, "Tệp đã được lưu với tên: " + filename, Toast.LENGTH_SHORT).show();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Toast.makeText(NoteEdit.this, "Quá trình lưu tệp bị lỗi.", Toast.LENGTH_SHORT).show();
			}
		}
	}
}
